package web.java.a_Filter;

import java.io.IOException;
import java.util.Enumeration;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
/**
 * Filter的生命周期
 * 首先Filter处于浏览器和服务器中间，当浏览器访问Servlet时，需要经过过滤器，当Servlet返回浏览器信息时，也需要经过过滤器
 * */
public class Demo01_Filter implements Filter{

	public Demo01_Filter() {
		System.out.println("1、过滤器的构造方法...");
	}
	
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		// TODO Auto-generated method stub
		System.out.println("2、过滤器的初始化...");
		//获取初始化参数
		String encoding=filterConfig.getInitParameter("encoding");
		System.out.println(encoding);
		Enumeration<String> enums=filterConfig.getInitParameterNames();
		while(enums.hasMoreElements()){
			String name=enums.nextElement();
			String value=filterConfig.getInitParameter(name);
			System.out.println(name+"="+value);
		}
	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse res,
			FilterChain chain) throws IOException, ServletException {
		// TODO Auto-generated method stub
		System.out.println("3、第一个过滤器执行方法...");
		//放行，到下一个过滤器或到Servlet
		chain.doFilter(req, res);
		System.out.println("5、Servlet执行完毕，返回到第一个过滤器...");
	}


	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		System.out.println("6、过滤器被销毁");
	}
}
